package com.mzkj.common.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * 上传图片到七牛工具类
 * Created by wangxw on 15/11/17.
 */
@Component("uploadImg2QiniuUtils")
public class UploadImg2QiniuUtils {
    private static Logger logger = LoggerFactory.getLogger(PropertiesLoader.class);
    private Auth auth;
    private UploadManager uploadManager;

    public UploadImg2QiniuUtils(String accessKey, String secretKey) {
        if (uploadManager == null) {
            uploadManager = new UploadManager();
        }
        if (auth == null) {
            auth = Auth.create(accessKey, secretKey);
        }
    }
    /**
     * 获取token
     *
     * @return
     */
    private String getUpToken() {
        return auth.uploadToken("file");
    }

    public QiniuRet upload(File file, String fileName) {
        QiniuRet ret = null;
        try {
            Response res = uploadManager.put(file, null, getUpToken());
            ret = res.jsonToObject(QiniuRet.class);
            logger.info(res.toString());
            logger.info(res.bodyString());
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时简单状态信息
            logger.error(r.toString());
            try {
                // 响应的文本信息
                logger.error(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
        //TODO 删除下载的图片
        file.delete();
        return ret;
    }


}
